from django.shortcuts import render
from django.shortcuts import redirect
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.text import slugify
from django.core.files.base import ContentFile

from . import forms
from . import utils
from . import models
from likes import models as like_models


class ShowingImages(LoginRequiredMixin, generic.View):

    def get(self, request):

        form = forms.ImageSelectionForm()
        list_of_images = models.Image.objects.filter(user=request.user)
        context = {'section': 'images',
                   'form': form,
                   'list_of_images': list_of_images}

        return render(request, 'images/show.html', context)


    def post(self, request):

        bound_form = forms.ImageSelectionForm(request.POST)

        if bound_form.is_valid():

            image_link = bound_form.cleaned_data['url']
            return redirect('images:create', slug=image_link)


class CreatingImage(LoginRequiredMixin, utils.ObjectDetailMixin, generic.View):

    model = models.Image
    form = forms.ImageCreateForm

    def get(self, request, slug):

        print(f'sssslug - {slug}')
        form = forms.ImageCreateForm(data={'url': slug})
        context = {'section': 'images', 'form': form, 'slug': slug}

        return render(request, 'images/create.html', context)


class ShowImage(generic.View):

    def get(self, request, slug):

        image = models.Image.objects.get(slug=slug)
        context = {'image': image}

        return render(request, 'images/show_image.html', context)


class UpdateImage(utils.ObjectDetailMixin, generic.View):

    model = models.Image
    form = forms.ImageUpdateForm

    def get(self, request, slug):

        image = models.Image.objects.get(slug=slug)
        form = forms.ImageUpdateForm(instance=image)
        context = {'section': 'images',
                   'image': image,
                   'form': form}

        return render(request, 'images/update.html', context)


class DeleteImage(generic.View):

    def get(self, request, slug):

        image = models.Image.objects.get(slug=slug)
        context = {'image': image}

        return render(request, 'images/delete.html', context)

    def post(self, request, slug):

        image = models.Image.objects.get(slug=slug)
        image.delete()

        return redirect('images:show')
